<template>
	<view class="play">
		<u-sticky>
			<view class="sticky">
				<view class="play-box">
					<video class="player" :autoplay="true" :src="url" :initial-time="initialtime" :title="detail.vod_name"
						:poster="detail.vod_pic" enable-play-gesture :play-strategy="2" @ended="handleNext"
						@timeupdate="videoTimeUpdateEvent"></video>
				</view>
				<u-cell-item :arrow="false">
					<view slot="title">
						<view class="u-line-1" style="max-width: 450upx;">
							<text selectable>{{ detail.vod_name }}</text>
						</view>
					</view>
					<text>来源：</text>
					<text>{{ siteInfo.name }}</text>
				</u-cell-item>
			</view>
		</u-sticky>
		<u-row :gutter="16" class="u-p-20">
			<u-col :span="4">
				<u-button size="medium" plain shape="circle" type="success">快搜</u-button>
			</u-col>
			<u-col :span="4">
				<u-button size="medium" plain shape="circle" type="success" @click="changeStar()">
					<text v-if="!starShow">收藏</text>
					<text v-else>已收藏</text>
				</u-button>
			</u-col>
			<u-col :span="4">
				<u-button size="medium" plain shape="circle" type="success" @click="handleShare">分享</u-button>
			</u-col>
		</u-row>
		<view class="box-info">
			<view class="name-box">
				<text class="name">{{ detail.vod_name }}</text>
			</view>
			<view class="info-box">
				<text>{{ detail.vod_area }}</text>
				<text class="gap">|</text>
				<text>{{ detail.vod_lang }}</text>
				<text class="gap">|</text>
				<text>{{ detail.type_name }}</text>
				<text class="gap">|</text>
				<text>{{ detail.vod_year }}</text>
			</view>
			<view class="info-box">
				<text>导演: {{ detail.vod_director }}</text>
			</view>
			<view class="info-box">
				<text>演员: {{ detail.vod_actor }}</text>
			</view>
			<view class="info-box">
				<text>简介:</text>
				<u-parse :html="detail.vod_content"></u-parse>
			</view>
		</view>
		<view v-if="playList.length== 0 && listChildren.length == 1 " class="play-single u-p-10">
			<u-cell-item title="选集(不分组)" :arrow="false" :border-bottom="false" />
			<view v-for="(item,index) in listChildren" :key="index" @click="playConfirm(item,index)">
				<u-tag :text="item.label" mode="dark" />
			</view>
		</view>
		<view class="paly-list" v-else>
			<u-cell-item title="选集" :arrow="false" :border-bottom="false" />
			<view class="play-group u-border-bottom ">
				<u-tag :text="item.label" :mode="currentGroup == index?'dark':'plain'" type="success"
					@click="groupChange(item,index)" v-for="(item,index) in playList" :key="index" />
			</view>
			<view class="paly-list-item">
				<u-tag :text="item.label" :mode="current == item?'dark':'plain'" v-for="(item,index) in listChildren"
					:key="index" @click="playConfirm(item,index)" />
			</view>
		</view>
		<u-select v-model="playShow" :list="playList" confirm-text="播放" @confirm="playConfirm"></u-select>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import http from "@/utils/request.js"
	import Tools from "@/utils/tools.js"
	export default {
		data() {
			return {
				siteKey: "",
				id: "",
				name: "",
				url: "",
				current: [],
				currentGroup: 0,
				listChildren: [],
				initialtime: 0,
				siteInfo: {
					name: '未知'
				},
				playShow: false,
				playList: [],
				detail: {
					"vod_time": "2023-10-07 13:45:02",
					"vod_id": "5632",
					"vod_name": "乌当堂堂家族",
					"vod_enname": "wudangtangtangjiazu",
					"vod_subname": "",
					"vod_letter": "W",
					"vod_color": "",
					"vod_tag": "",
					"type_id": "20",
					"type_name": "欧美剧",
					"vod_pic": "https://pic1.bdzyimg.com/upload/vod/20231003-1/c5ce83fdef25b288e6e0055a4fac2cf9.jpg"
				},
				starShow: true,
				videoUpdateCounter: 0
			};
		},
		onLoad(opt) {
			this.siteKey = opt.site
			this.id = opt.id
			this.getDetail(this.siteKey, this.id)
			this.checkStar()
			this.fetchFrom()
			// #ifdef H5
			// this.playList = AppTestData.playList.data
			// #endif
			// #ifdef APP-PLUS
			this.detail = {
				vod_name: '数据加载中...'
			}
			// #endif

		},
		methods: {
			async videoTimeUpdateEvent(e) {
				// 播放进度变化时触发timeupdate，event.detail = {currentTime, duration} 。触发频率 250ms 一次
				this.videoUpdateCounter += 1
				if (this.videoUpdateCounter % 40 === 0) {
					// 每10秒更新一下历史记录的时间进度
					this.videoUpdateCounter = 0
					await this.updateHistory(e.detail)
				}
			},
			fetchFrom() {
				if (Array.isArray(this.defcku.sites)) {
					let site = this.defcku.sites.find(t => t.key == this.siteKey)
					if (site) {
						this.siteInfo = site
					}
				}
			},
			updateHistory(detail) {
				if (!Array.isArray(this.settings.history)) {
					this.$u.vuex('settings.history', [])
				}

				let key = `${this.siteKey}-${this.id}`
				let index = this.settings.history.findIndex(t => t.key == key)
				let item = {
					key,
					currentTime: detail.currentTime,
					duration: detail.duration
				}
				if (index == -1) {
					this.settings.history.push(item)
					this.$u.vuex('settings.history', this.settings.history)
					return
				} else {
					this.settings.history.splice(index, 1, item)
				}
				this.$u.vuex('settings.history', this.settings.history)
			},
			async getDetail(key, id) {
				try {
					let site = this.defcku.sites.find(t => t.key == key)
					const res = await http.detail(site, id)
					if (res.errMsg) {
						return
					}
					// console.log(res)
					this.detail = res.data
					uni.setNavigationBarTitle({ title: this.detail.vod_name })
					let result = Tools.handlePlayList(res.m3u8List, this.detail.vod_name)

					if (result.group) {
						this.playList = result.data
						if (this.playList.length > 0) {
							this.currentGroup = 0
							this.listChildren = this.playList[0].children
							this.playConfirm(this.listChildren[0], 0)
						}
						return
					}
					// console.log(this.playList)
					// console.log(result)
					//节目少于分组数据
					if (result.data.length > 0) {
						this.currentGroup = 0
						this.listChildren = result.data
						this.playConfirm(this.listChildren[0], 0)
					}
					if (result.data.length == 0) {
						uni.showModal({
							title: '未嗅探到播放地址',
							content: JSON.stringify(res),
							showCancel: false
						})
					}
				} catch (err) {
					console.log(err)
				}

			},
			playConfirm(obj, index) {
				this.current = obj
				this.url = obj.value
				if (this.playList.length == 0 && this.listChildren.length == 1) {
					uni.setNavigationBarTitle({ title: `${this.detail.vod_name}` })
				} else {
					uni.setNavigationBarTitle({ title: `${this.detail.vod_name}(${ obj.label })` })
				}
				this.addHistory(obj.label, obj.value)
			},
			async addHistory(label, url) {
				let h = { ...this.detail }
				h.key = `${this.siteKey}-${this.id}`
				let index = this.settings.history.findIndex(t => t.key == h.key)
				if (index == -1) {
					this.settings.history.push(h)
					this.$u.vuex('settings.history', this.settings.history)
					return
				}
				this.settings.history.splice(index, 1, h)
				// console.log( this.settings.history)
				this.$u.vuex('settings.history', this.settings.history)
			},
			groupChange(obj, index) {
				this.currentGroup = index
				this.listChildren = obj.children
				// console.log(index)
			},
			async checkStar() {
				let key = `${this.siteKey}-${this.id}`
				if (Array.isArray(this.settings.favorite)) {
					let index = this.settings.favorite.findIndex(t => t.key == key)
					this.starShow = index !== -1
				}

			},
			async removeStar() {
				let key = `${this.siteKey}-${this.id}`
				let index = this.settings.favorite.findIndex(t => t.key == key)
				if (index !== -1) {
					this.settings.favorite.splice(index, 1)
					this.$u.vuex('settings.favorite', this.settings.favorite)
					this.$refs.uToast.show({ title: '移除收藏成功', type: 'success', duration: '2300' })
					this.starShow = false
					return
				}
			},
			async addStar() {
				let s = { ...this.detail }
				s.key = `${this.siteKey}-${this.id}`
				s.time = this.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM')
				let index = this.settings.favorite.findIndex(t => t.key == s.key)
				if (index == -1) {
					this.settings.favorite.push(s)
					this.$u.vuex('settings.favorite', this.settings.favorite)
					this.$refs.uToast.show({ title: '添加收藏成功', type: 'success', duration: '2300' })
					this.starShow = true
					return
				}
			},
			changeStar() {
				if (this.starShow) {
					this.removeStar()
				} else {
					this.addStar()
				}
			},
			handleShare() {
				if (!this.url) {
					this.$u.toast('未嗅探到资源！')
					return
				}
				let contents = `${this.detail.vod_name}\n${this.url}`
				uni.setClipboardData({
					data: contents,
				})
			},
			handleNext() {
				//视频无分组
				if (this.playList.length == 0) {
					let index = this.listChildren.findIndex(t => t == this.current)
					if (index < this.listChildren.length) {
						this.playConfirm(this.listChildren[index + 1], index + 1)
					} else {
						this.$u.toast('已经是最后一集')
					}
					return
				}
				for (let i = 0; i < this.playList.length; i++) {
					let row = this.playList[i]
					let index = row.children.findIndex(t => t == this.current)
					if (index == -1) {
						//到了
						continue
					}
					//找到了
					if (index < row.children.length - 1) {
						console.log('该分组内切换集')
						this.playConfirm(row.children[index + 1], index + 1)
						return
					} else if (i < this.playList.length) {
						console.log('已经是该分组最后一集')
						//已经是该分组最后一集
						this.groupChange(this.playList[i + 1], i + 1)
						this.playConfirm(this.listChildren[0], 0)
						return
					} else {
						//已经是最后一集
						this.$u.toast('已经是最后一集')
						return

					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.play {
		--n: 4;
		--w: 160upx;

		.play-box {
			.player {
				width: 100vw;
			}
		}

		.sticky {
			background-color: #FFF;
		}

		.icon-box {
			padding: 20px 10%;
			display: flex;
			justify-content: flex-end;
		}

		.box-info {
			padding: 10px;
			margin: 5px;
			color: #808080;
			border-radius: 10upx;
			border: 1px solid #EEE;
			// box-shadow: #EEE 5px 5px 3px;

			.name-box {
				width: 100%;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;

				.name {
					font-size: 40rpx;
				}
			}

			.info-box {
				margin-top: 20rpx;

				.gap {
					margin: 0 10rpx;
				}
			}
		}

		.play-single {
			height: 200upx;
			border: 0px solid #096;
		}

		.paly-list {
			padding: 10px;
			margin: 10px 5px;
			border-radius: 10upx;
			border: 1px solid #EEE;
			box-sizing: border-box;
			border-bottom: 150px;
			background-color: #FFF;
			min-height: 900upx;

			.play-group {
				display: flex;
				flex-wrap: wrap;

			}

			.u-tag {
				width: var(--w);
				margin: 5px calc((100% - var(--w) * var(--n))/var(--n)/2);
				text-align: center;
			}

			.paly-list-item {
				padding: 20px 0px;
				align-items: flex-end;
				display: flex;
				flex-wrap: wrap;
			}
		}

	}
</style>